package ae.pcfc.cldos.online.web.util;

import java.net.URLConnection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Request utils
 * 
 * @author arosa
 *
 */
public final class RequestUtils {
	
	private static final Set<String> resourcesExt = new HashSet<String>(){
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		{
			add("js"); add("css"); add("jpg"); add("png"); add("gif"); add("bmp");
		}
	};

	public static final Cookie getCookieByName(String cookieName, HttpServletRequest request){
		Cookie result = null;
		Cookie[] cookies = request.getCookies();
		for(int i=0; i<cookies.length && result==null; i++){
			if(cookies[i].getName().equals(cookieName))
				result = cookies[i];
		}
		return result;
	}
	
	public static final String getCookieValueByCookieName(String cookieName, HttpServletRequest request){
		String result = null;
		Cookie cookie = getCookieByName(cookieName, request);
		if(cookie!=null){
			result = cookie.getValue();
		}
		return result;
	}
	
	public static final Boolean isResourceRequest(HttpServletRequest request){
		Boolean result = Boolean.FALSE;
		String requestedUrl = request.getRequestURI();
		
		String ext = requestedUrl.substring(requestedUrl.lastIndexOf('.')+1, requestedUrl.length());
		if(resourcesExt.contains(ext))
			result = Boolean.TRUE;
		
		return result;
	}
	
	public static final void copyHeaders(HttpServletResponse out, URLConnection in){
		Map<String, List<String>> headers = in.getHeaderFields();
		for(Entry<String, List<String>> header : headers.entrySet()){
			for(String headerValue : header.getValue()){
				if(header.getKey()!=null && headerValue!=null){
					out.addHeader(header.getKey(), headerValue);
				}
			}
		}
	}
}
